<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message,Modal } from '@arco-design/web-vue'
import api from '@/api'

const switchValue = ref('')
const $route = useRoute()
const $router = useRouter()

const keyword = ref('')
const keyword2 = ref('')
const keyword3 = ref('')
const listData = ref([])
const userData = ref([])
const userDataDetail = ref([])
const courseData = ref([])
const sectionData = ref([])
const taskData = ref([])
let cl=[...new Set(courseData.value)];
let sl_all=[...new Set(sectionData.value)];
let sl
const getListData = async () => {
  try {
    const res = await api.get('/exercise', {
      params: {
        keyword: keyword.value,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    listData.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
getListData()

const getTaskData = async (exercise_id) => {
  try {
    if(exercise_id==0){
      exercise_id = formData2.value.exercise_id
    }
    const res = await api.get('/exercise/detail', {
      params: {
        exercise_id: exercise_id,
        keyword: keyword2.value,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    taskData.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}

const getUserData = async (exercise_id) => {
  try {
    if(exercise_id==0){
      exercise_id = formData2.value.exercise_id
    }
    const res = await api.get('/exercise/user', {
      params: {
        exercise_id: exercise_id,
        keyword: keyword3.value,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    userData.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}

const getUserDataDetail = async (result_id) => {
  try {
    const res = await api.get('/exercise/user_detail', {
      params: {
        result_id: result_id,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    userDataDetail.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}

const getCourseData = async () => {
  try {
    const res = await api.get('/courses/options', {
    })
    console.log('res', res)
    courseData.value = res
    cl=[...new Set(courseData.value)];
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
getCourseData()

const getSectionData = async () => {
  try {
    const res = await api.get('/sections/options', {
    })
    console.log('res', res)
    sectionData.value = res
    sl_all=[...new Set(sectionData.value)];
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
getSectionData()

const formVisible = ref(false)
const formVisible2 = ref(false)
const formVisible3 = ref(false)
const formVisible4 = ref(false)
const formVisible5 = ref(false)
const formLoading = ref(false)
const formRef = ref()
const formRef2 = ref()
const formItem = ref(null)
const formItem2 = ref(null)
const formData = ref({
  name: '',
})

const formData2 = ref({
  exercise_id: '',
  question_text: '',
  course_id: '',
  section_id: '',
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写训练名称',
    },
  ],
}

const formRules2 = {
  question_text: [
    {
      required: true,
      message: '请填写问题描述',
    },
  ],
  course_id: [
    {
      required: true,
      message: '请选择课程',
    },
  ],
  section_id: [
    {
      required: true,
      message: '请选择视频',
    },
  ],
}

const create = () => {
  formRef.value?.resetFields()
  formItem.value = null
  formVisible.value = true
}

const create2 = () => {
  formRef2.value?.resetFields()
  formItem2.value = null
  formVisible3.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.name = item.name
  formVisible.value = true
}

const update2 = (item) => {
  formRef2.value?.resetFields()
  formItem2.value = item
  formData2.value.question_text = item.question_text
  formData2.value.course_id = item.course_id
  sel_course(item.course_id)
  formData2.value.section_id = item.section_id
  formVisible3.value = true
}

const setTask = (record) => {
  getTaskData(record.id)
  formVisible2.value = true
  formData2.value.exercise_id = record.id
}

const viewResult = (record) => {
  getUserData(record.id)
  formVisible4.value = true
  formData2.value.exercise_id = record.id
}

const userDetail = (record) => {
  getUserDataDetail(record.id)
  formVisible5.value = true
}
const toJump = (url) => {
  console.log('router', $router.push(url))
  $router.push(url)
}

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }
  formLoading.value = true
  try {
    if (formItem.value) {
      await api.put('exercise/' + formItem.value.id, formData.value)
    } else {
      await api.post('exercise', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }
  formLoading.value = false
  return false
}

const formSubmit2 = async () => {
  if (await formRef2.value.validate()) {
    return false
  }
  formLoading.value = true
  try {
    if (formItem2.value) {
      await api.put('exercise/detail/' + formItem2.value.id, formData2.value)
    } else {
      await api.post('exercise/detail', formData2.value)
    }
    formRef2.value?.resetFields()
    formVisible3.value = false
    getTaskData()
  } catch (error) {
    console.error(error)
  }
  formLoading.value = false
  return false
}


const del = (record) => {
  Modal.confirm({
    title: '删除',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete(`/exercise/${record.id}`)
      getListData()
    },
  })
}

const delTask = (record) => {
  Modal.confirm({
    title: '删除',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete(`/exercise/detail/${record.id}`)
      getTaskData()
    },
  })
}

const createAudio = async (record) => {
  formLoading.value = true
  try {
    await api.post('exercise/create_audio', {id:record.id,question_text:record.question_text})
    getTaskData()
  } catch (error) {
    console.error(error)
  }
  formLoading.value = false
  return false
}

const sel_course = (event) => {
  sl=[];
  formItem2.section_id=''
  sl_all.forEach((item, index) => {
    if(item.course_id==event)sl.push(item)
  })
}

const audios=ref();
const audio_url=ref('');

const playAudio = (path) => {
  if(path != audio_url.value){
    audio_url.value=''
    let timeout = setTimeout(()=>{
      audio_url.value=path
      clearTimeout(timeout)
    },100)
  }
  let playout = setTimeout(()=>{
    audios.value.currentTime=0
    audios.value.play()
    clearTimeout(playout)
  },300)
}
</script>

<template>
  <div class="page">
    <div class="header">
      <div>
        <a-input-search
          :style="{ width: '320px' }"
          v-model="keyword"
          placeholder="群组名称模糊查询"
          button-text="查询"
          @search="getListData"
          search-button
        />
      </div>
      <a-space>
        <a-button type="primary" @click="create">添加训练</a-button>
      </a-space>
    </div>

    <a-table :data="listData">
      <template #columns>
        <a-table-column title="序号" :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column
          title="训练名称"
          data-index="name"
        ></a-table-column>
        <a-table-column
          title="参与人数"
          data-index="user_count"
        ></a-table-column>
        <a-table-column
          title="问题数"
          data-index="detail_count"
        ></a-table-column>

        <a-table-column title="操作" align="center" :width="300">
          <template #cell="{ record }">
            <a-space>
              <a-button
                type="primary"
                size="mini"
                @click="setTask(record)"
                >配置题目</a-button
              >
              <a-button
                type="primary"
                size="mini"
                @click="viewResult(record)"
                >查看结果</a-button
              >
              <a-button
                type="primary"
                size="mini"
                @click="update(record)"
                >编辑</a-button
              >
              <a-button
                type="primary"
                size="mini"
                status="danger"
                @click="del(record)"
                >删除</a-button
              >
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <a-modal
      v-model:visible="formVisible"
      title="基础设置"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules">
        <a-form-item field="name" label="训练名称">
          <a-input v-model="formData.name" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="formVisible2"
      title="配置题目"
      :ok-loading="formLoading"
      :hideCancel="true"
      okText="关闭"
      width="auto"
    >
      <div class="header">
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            v-model="keyword2"
            placeholder="题目模糊查询"
            button-text="查询"
            @search="getTaskData(0)"
            search-button
          />
        </div>
        <a-button @click="create2" type="primary"
          >新建题目</a-button
        >
      </div>

      <a-table :data="taskData">
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column
            title="问题描述"
            data-index="question_text"
          >
          </a-table-column>
          <a-table-column
            title="关联课程"
          >
            <template #cell="{ record }">
              {{record.course.name}}
            </template>
          </a-table-column>
          <a-table-column
            title="关联章节"
          >
            <template #cell="{ record }">
              {{record.section.name}}
            </template>
          </a-table-column>
          <a-table-column
            title="是否有音频"
          >
            <template #cell="{ record }">
              <span v-if="record.question_audio==''">未生成</span>
              <span v-else>已生成</span>
            </template>
          </a-table-column>
          <a-table-column title="操作" align="center" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  size="mini"
                  @click="createAudio(record)"
                  >生成音频</a-button
                >
                <a-button
                  type="primary"
                  size="mini"
                  @click="update2(record)"
                  >编辑</a-button
                >
                <a-button
                  type="primary"
                  status="danger"
                  size="mini"
                  @click="delTask(record)"
                  >删除</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>

    <a-modal
      v-model:visible="formVisible3"
      title="新建题目"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit2"
    >
      <a-form ref="formRef2" :model="formData2" :rules="formRules2">
        <a-form-item field="name" label="问题描述">
          <a-input v-model="formData2.question_text" allow-clear />
        </a-form-item>
        <a-form-item field="course_id" label="关联课程">
          <a-select v-model="formData2.course_id" :style="{width:'320px'}" @change="sel_course" placeholder="请选择课程" allow-search>
            <a-option
              v-for="item in cl"
              :value="item.id"
            >
            {{item.name}}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="course_id" label="关联视频">
          <a-select v-model="formData2.section_id" :style="{width:'320px'}" placeholder="请选择视频" allow-search>
            <a-option
              v-for="item in sl"
              :value="item.id"
            >
            {{item.name}}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>


    <a-modal
      v-model:visible="formVisible4"
      title="训练结果"
      :ok-loading="formLoading"
      :hideCancel="true"
      okText="关闭"
      width="auto"
    >
      <div class="header">
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            v-model="keyword3"
            placeholder="用户模糊查询"
            button-text="查询"
            @search="getUserData(0)"
            search-button
          />
        </div>
      </div>

      <a-table :data="userData">
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column
            title="用户姓名"
            data-index="user_name"
          >
          </a-table-column>
          <a-table-column
            title="用户账号"
            data-index="user_username"
          >
          </a-table-column>
          <a-table-column
            title="训练进度"
          >
            <template #cell="{ record }">
              {{record.progress}}/{{record.total_question}}
            </template>
          </a-table-column>
          <a-table-column
            title="完成状态"
          >
            <template #cell="{ record }">
              <span v-if="record.status==0">未开始</span>
              <span v-if="record.status==1">进行中</span>
              <span v-if="record.status==2">已完成</span>
            </template>
          </a-table-column>
          <a-table-column title="操作" align="center" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  size="mini"
                  @click="userDetail(record)"
                  >详情</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>

    <a-modal
      v-model:visible="formVisible5"
      title="结果详情"
      :ok-loading="formLoading"
      :hideCancel="true"
      okText="关闭"
      width="auto"
    >
      <a-table :data="userDataDetail">
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column
            title="问题描述"
          >
            <template #cell="{ record }">
              {{record.question.question_text}}
            </template>
          </a-table-column>
          <a-table-column
            title="回答"
            data-index="audio_text"
          >
          </a-table-column>
          <a-table-column title="操作" align="center" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  size="mini"
                  @click="playAudio(record.audio_path)"
                  >播放音频</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
  <audio style="display:none" ref="audios" v-if="audio_url">
    <source :src="audio_url"/>
  </audio>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  justify-content: space-between;
}
</style>
